-- NewBagMultPanel

local ListViewVertical = require("app.widget.listview.ListViewVertical")
local NewBagRender = import(".renders.NewBagRender")
local IconRender = require("app.widget.renders.IconRender")

local ClassRef = app.mvc.createPanelClass(...)

local OPEN_TAG = 1
local CLOSE_TAG = 2
local PLAYING_TAG = 3

-- 初始化最大批量操作格子数
local INIT_MULT_CELL_NUM = 25
-- 每次添加的格子数量
local ADD_MULT_CELL_NUM = 4
-- 分解获得一列显示5个
local DROP_ITEM_MAX_NUM = 5

function ClassRef.create(node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.NewBagMultPanel))
	if not node then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	local timeline = self:getTimeline()
	if timeline then
		self:getTimeline():gotoFrameAndPause(0)
		self:getTimeline():setLastFrameCallFunc(handler(self, self._onAnimationPlayEnd))
	end
	
	self.super.init(self, data)
	self._curStatus = CLOSE_TAG
	self._nextStatus = CLOSE_TAG
	self:setContentSize( self._ui["Panel"]:getContentSize() )
	display.setCascadeOpacityEnabled(self._ui["Panel"], true)


	self._ui["Panel/Button_close"]:addClickEventListener(function()
		executeFunc(self._onOperate, "close")
	end)

	self._ui["Panel/Button_tick"]:addClickEventListener(function(sender, eventType)
		local isBright = self._ui["Panel/Button_tick"]:isBright()
		self._ui["Panel/Button_tick"]:setBright(not isBright)
		executeFunc(self._onOperate, "autoChoose", isBright)
	end)

	self._ui["Panel/Button_ok"]:addClickEventListener(function()

		local selectItemTypeList = {} -- 选中物品的类型列表
		local selectItemUidList = {} -- 选中物品的uid列表
		local selectItemCountList = {} -- 数量列表

		local haveJewelInMultRenders = false -- 选中物品的中是否含有宝石
		local items = self._listview:getData()

		for _,renderData in ipairs(items) do
			if Enums.ItemBagType.jewel == tonumber( renderData.itemBagType ) then
				haveJewelInMultRenders = true
			end
			table.insert( selectItemTypeList, renderData.itemBagType )
			table.insert( selectItemUidList, renderData.uid )
			table.insert( selectItemCountList, renderData.amount )
		end
		if #selectItemUidList <= 0 then
			display.pushToast( L("tips_3000298") )
			return
		else
			if haveJewelInMultRenders then
				local confirmDialog = display.newConfirmDialog(L("lua_code_text_363"),
					function()
						executeFunc(self._onOperate, "doMultAct", {selectItemTypeList, selectItemUidList, selectItemCountList, self._dropItemNum, self._dropItemIconPath})
					end)
				UIHandler:addPopDialog(confirmDialog)
			else
				executeFunc(self._onOperate, "doMultAct", {selectItemTypeList, selectItemUidList, selectItemCountList, self._dropItemNum, self._dropItemIconPath})
			end
		end
	end)


	local params = {
		renderClass = NewBagRender,
		isMultipleLayer = true,
		perNum = 5,
        gapY = 2,
		cellEventProxy = function(eventName, itemData)
			executeFunc(self._onOperate, "BagMultPanel_clickItem", itemData)
		end,
	}

	self._listview = ListViewVertical.new(self._ui["Panel/ScrollView"], params)

    self._dropItemNum = {}
    self._dropItemIconPath = {}
    self._dropItemListView = self._ui["Panel/ListView"]
    self._dropItemListView.createRender = function(list, idx)
        local items = list:getItems()
        local render = items[idx]
        if nil == render then
            render = IconRender.create()
            render:setTipEnable(true)
            list:pushBackCustomItem(render)
        end
        render:setVisible(true)
        return render
    end
    self:refreshDecomposeGotNum()
end

-- data = 3(批量分解)
function ClassRef:refresh()
	self._ui["Panel/Button_tick"]:setBright( true )
	self:refreshDecomposeGotNum()
end

function ClassRef:onOperate(cb)
	self._onOperate = cb
end

function ClassRef:refreshDecomposeGotNum( breakDropList )
    if self._dropItemNum and #self._dropItemNum > 0 then
        for i = #self._dropItemNum, 1, -1 do
            if self._dropItemNum[i] ~= nil then
                table.remove(self._dropItemNum, i)
            end
        end
    end
    if self._dropItemIconPath and #self._dropItemIconPath > 0 then
        for i = #self._dropItemIconPath, 1, -1 do
            if self._dropItemIconPath[i] ~= nil then
                table.remove(self._dropItemIconPath, i)
            end
        end
    end

    if self._dropItemListView then
        self._dropItemListView:removeAllChildren()
    end

	if breakDropList then -- { type = { tid = num } }
		local DropType
		local DropId
		local DropNum
        local DropItem
        local DropItemIconPath
        local idx = 0
        local render
		for k,v in pairs(breakDropList) do
			DropType = k
			for k2,v2 in pairs(v) do
				idx = idx + 1
				DropId = k2
				DropNum = v2
                DropItem = UD:parseRewardToBagItem(DropType .. "|" .. DropId .. "|" .. DropNum)
                DropItemIconPath = DropItem:getIcon()

                table.insert(self._dropItemNum, DropNum)
                table.insert(self._dropItemIconPath, DropItemIconPath)

                render = self._dropItemListView:createRender(idx)
                render:setData(DropItem)
            end
        end
    end
    local count = #self._dropItemListView:getItems()
    if count < 5 then
        for i = count + 1, DROP_ITEM_MAX_NUM do
            local render = self._dropItemListView:createRender(i)
            render:setData(nil)
        end
    end
end

function ClassRef:getScrollView()
	return self._listview
end

function ClassRef:remove()

end

function ClassRef:canOpen()
	return self._curStatus == CLOSE_TAG
end

function ClassRef:canClose()
    return self._curStatus == OPEN_TAG
end

function ClassRef:isOpen()
	return self._curStatus == OPEN_TAG
end

function ClassRef:_onAnimationPlayEnd()
	if self._nextStatus == CLOSE_TAG then
		executeFunc(self._onOperate, 'closeAnimationEnd')
	end
	self._curStatus = self._nextStatus
end

function ClassRef:playOpen()
	if not self:canOpen() then
		return
	end
	self._curStatus = PLAYING_TAG
	self._nextStatus = OPEN_TAG
	self:getTimeline():play('open', false)
end

function ClassRef:playClose()
	if not self:canClose() then
		return
	end
	self._curStatus = PLAYING_TAG
	self._nextStatus = CLOSE_TAG

	self:getTimeline():play('close', false)
end

function ClassRef:reloadListView(items)
	self._listview:reloadData(items, {forceAlign = true, startIndex = 1, minDataLen = INIT_MULT_CELL_NUM})
end

function ClassRef:addItem(item)
	if not item then
		return
	end
	local items = self._listview:getData()
	table.insert(items, item)
	self._listview:reloadData(items, {forceAlign = true, minDataLen = INIT_MULT_CELL_NUM})
end

function ClassRef:deleteItem(item)
	if not item then
		return
	end
	local items = self._listview:getData()
	for k ,v in ipairs(items) do
		if v.uid == item.uid then
			table.remove(items, k)
			break
		end
	end
	self._listview:reloadData(items, {forceAlign = true, minDataLen = INIT_MULT_CELL_NUM})
end

return ClassRef
